package com.wanxi.util;

import java.sql.*;

/**
 * @author Li
 * @Date 2023/5/4 15:30
 */
public class JDBC {
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/lawyer_firm?serverTimezone=UTC&characterEncoding=UTF-8";
    private static PreparedStatement preparedStatement = null;

    //加载驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //连接数据库
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //编译SQL语句
    public static int update(String sql) {

        try {

            preparedStatement = getConnection().prepareStatement(sql);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cole();
        }
        return -1;
    }

    public static ResultSet query(String sql) {

        try {
            preparedStatement = getConnection().prepareStatement(sql);
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void cole() {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Integer count(String sql) {
        ResultSet query = JDBC.query(sql);
        try {
            while (query.next()) {
                return query.getInt("count");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
